/**
 * 应用的核心js文件
 *
 *
 */
var grErp = angular.module('gr-erp',[]);
var webroot="/erp/index.php?s=/";
(function(){
    hrefValue = window.location.href; //获取当前页面的地址
    alertUrls = ['127.0.0.1','localhost'];   // //追加如：['www.bbb.com', 'bbb.com', 'abc.bbb.com']
    for (key in alertUrls) {
        if (String(hrefValue).indexOf(alertUrls[key]) >= 0) {
            webroot="/erp/index.php?s=/";
            break; //直接跳出循环
        }
    }
    realUrls = ['180.150.187','http://erp.guoran100.com/'];
    for (key in realUrls) {
        if (String(hrefValue).indexOf(realUrls[key]) >= 0) {
            webroot="/index.php?s=/";
            break; //直接跳出循环
        }
    }
})();
loadingStart=function(){
    var loadModal=$('#loadingModal');
    loadModal.modal({backdrop: 'static', keyboard: false});

}
loadingEnd=function(){
    var loadModal=$('#loadingModal');
    loadModal.modal('hide');
}
grErp.filter('count_type',function(){
    return function(type){
        var out="";
        switch (parseInt(type)){
            case 1:
                out="斤";
                break;
            case 2:
                out="个";
                break;
            case 3:
                out="斤";
                break;
            case 4:
                out="个";
                break;
            default :
                out="斤";
                break;
        }
        return out;
    }
});
grErp.filter('strToNum',function(){
    return function(str){
        var reg=/\d+[\.\d+]*/
        try{
            var result=String(str).match(reg);
            if(result!=null){
                return parseFloat(result[0],2);
            }else{
                return 0
            }
        }catch(err){
            return 0;
        }
    }
});
grErp.filter('getSpecUnit',function(){
    return function(spec){
        reg=/[0-9](?=[\D]*$)/
        try{
            result=spec.match(reg);
            if(result!=null){
                return spec.substr(result['index']+1,1);
            }else{
                return 0;
            }
        }catch(err){
            return 0;
        }
    }
});
grErp.filter('getSpecUnitWithNum',function(){
    return function(spec){
        reg=/[0-9](?=[\D]*$)/
        var unit;
        var num;
        try{
            var result = spec.match(reg);
            unit = spec.substr(result['index']+1,1);
        }catch(err){
        }
        reg2=/[0-9]+(?=[\D]*$)/
        try{
            var result2=spec.match(reg2);
            num = result2[0];
        }catch(err){}
        if(num&&unit){
            return String(num)+unit;
        }else{
            return;
        }
    }
});
grErp.filter('getLaterUnit',function(){
    return function(spec){
        reg=/\//
        try{
            result=spec.match(reg);
            if(result!=null){
                return spec.substr(result['index']+1,1);
            }else{
                return 0;
            }
        }catch(err){
            return 0;
        }
    }
});
grErp.filter('getUnit',function(){
    return function(spec){
        reg=/\//
        reg2=/[0-9](?=[\D]*$)/
        try{
            result=spec.match(reg);
            result2=spec.match(reg2);
            if(result!=null&&result2!=null){
                return String(spec.substr(result2['index']+1,1))+"/"+String(spec.substr(result['index']+1,1));
            }else{
                return 0;
            }
        }catch(err){
            return 0;
        }
    }
});
grErp.filter('isValidValue',function(){
    return function(value){
        if(value!=null&&value!=undefined&&value!=""){
            return true;
        }else{
            return false;
        }
    }
});
grErp.filter('grEncode',function(){
    return function(value){
        var part = value.substr(0,8);
        var part2 = value.substr(8,8);
        var y = Math.floor(Math.random()*10000);
        if(part2!=""){
            y = Math.floor(Math.random()*10);
        }
        var m = part.substr(4,2);
        var d = part.substr(6,2);
        var en_code = m+''+y+''+d;
        return part2+en_code;
    }
})

grErp.controller('TestCtrl',['$scope',function($scope){
    $scope.checkVersion = function(){
        alert('hello there~');
    };
}]);
grErp.directive('select2', function (select2Query) {
    return {
        restrict: 'A',
        scope: {
            config: '=',
            ngModel: '=',
            select2Model: '='
        },
        link: function (scope, element, attrs) {
            // 初始化
            var tagName = element[0].tagName,
                config = {
                    allowClear: true,
                    multiple: !!attrs.multiple,
                    placeholder: attrs.placeholder || ' '   // 修复不出现删除按钮的情况
                };

            // 生成select
            if(tagName === 'SELECT') {
                var $element = $(element);
                delete config.multiple;
                $element
                    .prepend('<option value=""></option>')
                    .val('')
                    .select2(config);
                return false;
            }
        }
    }
});
grErp.factory('select2Query', function ($timeout) {
    return {
    }
});
grErp.controller('RejectCtrl',['$scope',function($scope){
    $scope.items = [{inventory:"",cnt:"",id:""}];
    $scope.moreItem = function(){
        $scope.items.push({inventory:"",cnt:"",id:""});
    }
    $scope.init=function(o){
        $scope.product = o;
    }
    $scope.select = function($index,x){
        var proIndex = parseInt(x);
        if(isNaN(proIndex)){
            return false;
        }
        $scope.items[$index].id = $scope.product[proIndex].id;
    }
    $scope.removeItem = function($index){
        if(!confirm('是否确定删除?')) return;
        $scope.items.splice($index,1);
    }

}]);
grErp.controller('StorageInCtrl',['$scope','subProFactory',function($scope,subProFactory){
    $scope.init=function(){
        subProFactory.ajaxGetSubproInventoryProductList().then(function(d){
            $scope.product=d
        });
    }
}]);
grErp.controller('InventoryCtrl',['$scope','$filter','inventoryFactory',function($scope,$filter,inventoryFactory){
    $scope.items = [{BIN:'初始化',notybz:false}];
    $scope.moreItem = function(){
        $scope.items.push({BIN:'初始化',notybz:false});
    }
    $scope.init=function(t,i){
        inventoryFactory.getproductlist(t).then(function(d){
            $scope.product = d;
        });
    }
    //盘点功能
    $scope.checkinit=function(){
        inventoryFactory.ajaxcheckinventorylist().then(function(d){
            $scope.product = d;
            console.log(d);
        });
    }
    //盘点商品选择
    $scope.checkproselect=function($index,x){
        BIN=$scope.product[x].BIN;
        if(BIN!=undefined&&BIN!=""){
            $scope.items[$index].BIN=BIN;
        }else{
            $scope.items[$index].BIN="";
            alert("请选择商品");
        }
        inventoryFactory.checkbatchlist(BIN).then(function(d){
            console.log(d);
            $scope.b_invens = d;
        });
    }
    //盘点批次选择
    $scope.checkbatchoselect=function($index,wb){
        batch_obj=JSON.parse(wb);
        warn_batch=batch_obj.warn_batch;
        if(warn_batch!=undefined&&warn_batch!=""){
            $scope.items[$index].warnbatch=warn_batch;
        }else{
            $scope.items[$index].warnbatch="";
            alert("请选择批次");
        }
        $scope.items[$index].inventory=parseInt(batch_obj.cnt);
    }
    $scope.outinit=function(cnt){
        inventoryFactory.getinventory().then(function(d){
            $scope.product = d;
        });
        inventoryFactory.getbatchlist('',cnt).then(function(d){
            $scope.b_invens = d;
        })
    }
    $scope.addproselect = function($index,x){
        $scope.items[$index].BIN = x;
        inventoryFactory.getybzBINlist(x).then(function(d){
            $scope.items[$index].ybzBINlist = d;
        });

    }
    $scope.ybzBINselect=function($index,x){
        inventoryFactory.getybzlist(x).then(function(d){
            $scope.items[$index].ybzlist = d;
        });
    }
    $scope.outproselect = function($index,x){
        $scope.items[$index].BIN = x;
    }
    $scope.outbatchoselect = function($index,wb){
        wb = JSON.parse(wb);
        $skip = true;
        angular.forEach($scope.items,function(data,index,array){
            if(data.warnbatch == wb.warn_batch&&wb.BIN == data.BIN){
                $scope.items[$index].inventory = "";
                $scope.items[$index].warnbatch = "";
                $scope.items.splice($index,1);
                alert('相同商品相同预警批次存在，已删除');
                $skip = false;
            }
        });
        if($skip){
            $scope.items[$index].inventory = parseInt(wb.cnt);
            $scope.items[$index].warnbatch = wb.warn_batch;
        }

    }
    $scope.cnt = function($index){
        console.log($scope.items[$index].inventory)
        i = $scope.items[$index].inventory
        if(i == undefined){
            $scope.items[$index].cnt="";
            alert("请重新选择出库商品和批次");
            return false;
        }

        if($scope.items[$index].cnt>$scope.items[$index].inventory){
            $scope.items[$index].cnt="";
            alert("数量过大,重新输入");
            return false;
        }
    }
    $scope.removeItem = function($index){
        if(!confirm('是否确定删除?')) return;
        $scope.items.splice($index,1);
    }
    $scope.getproductlist = function(type){
        inventoryFactory.getproductlist(type).then(function(d){
            $scope.product = d;
        });
    }
    $scope.rejectselect = function($index,v){
        $scope.items[$index].BIN = v;
        inventoryFactory.getbatchlist(v).then(function(d){
            $scope.items[$index].batchlists = d;
        });
    }
}]);
grErp.factory('inventoryFactory',['$http','$q',function($http,$q){
    var service={};
    service.getybzlist = function(BIN){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Inventory/ajaxgetybzlist",
            params:{BIN:BIN}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    };
    service.getybzBINlist = function(BIN){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Inventory/ajaxgetybzBINlist",
            params:{BIN:BIN}
        }).success(function(data,status,headers,config){
            console.log(data);
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    };
    service.getbatchlist = function(BIN,cnt){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Inventory/ajaxgetbatchlist",
            params:{BIN:BIN,cnt:cnt}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    };
    //获取盘点商品列表
    service.ajaxcheckinventorylist = function(){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Inventory/ajaxcheckinventorylist",
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    };
    //获取选中商品批次
    service.checkbatchlist = function(BIN){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Inventory/ajaxcheckbatchlist",
            params:{BIN:BIN}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    };
    service.getproductlist = function(type){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Inventory/ajaxgetproductlist",
            params:{type:type}
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    };
    service.getinventory = function(){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Inventory/ajaxgetinventory",
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    };
    return service;
}]);
grErp.factory('subProFactory',['$http','$q',function($http,$q){
    var service={};
    /**
     *ajax获取基础定价预处理批次列表
     * @returns {*}
     */
    service.ajaxGetSubproInventoryProductList=function(){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Subpro/ajaxGetSubproProductList",
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    service.ajaxGetSubPro=function(){
        var deferred=$q.defer();
        $http({
            method:'POST',
            url:webroot+"Admin/Subpro/ajaxGetSubPro",
        }).success(function(data,status,headers,config){
            deferred.resolve(data);
        }).error(function(data,status,headers,config){
            deferred.reject(data);
        });
        return deferred.promise;
    }
    return service;
}]);
